﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using RestSemitaService.Models;

namespace RestSemitaService.Controllers
{
    public class MessengerLocationController : ApiController
    {
        // GET api/location
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/location/5
        public string Get(string invoice_no)
        {
            try
            {
                SqlConnection thisConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
                thisConnection.Open();
                SqlCommand thisCommand = thisConnection.CreateCommand();
                thisCommand.CommandText = @"
                SELECT invoice_header.invoice_no, 
       invoice_header.customer_id,                 
       invoice_header.invoice_status,               
       invoice_header.address_text,                  
       invoice_header.messenger_id,                   
       messenger_location.last_update_location,        
       messenger_location.last_update_date 
FROM   invoice_header   
       INNER JOIN     
       messenger_location
       ON invoice_header.messenger_id = messenger_location.messenger_id
WHERE  invoice_header.invoice_no = @invoice_no
       AND last_update_date = (SELECT max(last_update_date)
                               FROM   messenger_location
                               WHERE  messenger_id = invoice_header.messenger_id)
	   AND messenger_location.deliver_date = CONVERT(VARCHAR(10),CURRENT_TIMESTAMP,126)	";
                thisCommand.Parameters.AddWithValue("@invoice_no", invoice_no);
                using (SqlDataReader reader = thisCommand.ExecuteReader())
                {
                    List<MessengerLocation> MessengerLocation = new List<MessengerLocation>();
                    while (reader.Read())
                    {
                        string _invoice_no = reader["invoice_no"].ToString();
                        string _customer_id = reader["customer_id"].ToString();
                        string _messenger_id = reader["messenger_id"].ToString();
                        string _invoice_status = reader["invoice_status"].ToString();
                        string _address_text = reader["address_text"].ToString();
                        string _last_update_location = reader["last_update_location"].ToString();
                        string _last_update_date = reader["last_update_date"].ToString();
                        MessengerLocation.Add(new MessengerLocation
                        {
                            InvoiceNo = _invoice_no,
                            CustomerId = _customer_id,
                            MessengerId = _messenger_id,
                            InvoiceStatus = _invoice_status,
                            AddressText = _address_text,
                            LastUpdateLocation = _last_update_location,
                            LastUpdateDate = _last_update_date
                        });
                    }
                    reader.Close();
                    thisConnection.Close();
                    string json = JsonConvert.SerializeObject(new
                    {
                        MessengerLocation = MessengerLocation
                    });
                    return json;
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                return e.StackTrace + " \n >>>>>>>>>>>>>>>>> \n" + e.Message;
            }
        }

		// GET api/location/5
		public string Get(string messenger_id, string address_gps)
		{
			try
			{
				SqlConnection thisConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
				thisConnection.Open();
				SqlCommand thisCommand = thisConnection.CreateCommand();
				thisCommand.CommandText = @"update	messenger_location 
											set		last_update_location = @address_gps, 
													last_update_date = CURRENT_TIMESTAMP 
											where	messenger_id = @messenger_id
													and deliver_date = convert(varchar, getdate(), 101)";

				thisCommand.Parameters.AddWithValue("@messenger_id", messenger_id);
				thisCommand.Parameters.AddWithValue("@address_gps", address_gps);

				if (thisCommand.ExecuteNonQuery() > 0)
				{
					thisConnection.Close();
					return "true";
				}
				else
				{
					thisConnection.Close();
					return "false";
				}
			}
			catch (SqlException e)
			{
				Console.WriteLine(e.Message);
				return e.StackTrace + " \n >>>>>>>>>>>>>>>>> \n" + e.Message;
			}
		}


        // POST api/location
        // update address_gps for customer
        public string Post(string messenger_id, string address_gps)
        {
            try
            {
                SqlConnection thisConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
                thisConnection.Open();
                SqlCommand thisCommand = thisConnection.CreateCommand();
                thisCommand.CommandText = @"update messenger_location set last_update_location = @address_gps, 
                last_update_date = CURRENT_TIMESTAMP 
                where messenger_id = @messenger_id
                and deliver_date = convert(varchar, getdate(), 101)";
                thisCommand.Parameters.AddWithValue("@messenger_id", messenger_id);
                thisCommand.Parameters.AddWithValue("@address_gps", address_gps);
                if (thisCommand.ExecuteNonQuery() > 0)
                {
                    thisConnection.Close();
                    return "true";
                }
                else
                {
                    thisConnection.Close();
                    return "false";
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                return e.StackTrace + " \n >>>>>>>>>>>>>>>>> \n" + e.Message;
            }
        }

        // PUT api/location/5
        public string Put(string messenger_id, string start_location)
        {
            try
            {
                SqlConnection thisConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
                thisConnection.Open();
                SqlCommand thisCommand = thisConnection.CreateCommand();
                thisCommand.CommandText = @" insert into messenger_location (deliver_date, messenger_id, 
                start_location, start_time, last_update_location, last_update_date) values 
                (CURRENT_TIMESTAMP, @messenger_id, @start_location, CURRENT_TIMESTAMP, null, null)";
                thisCommand.Parameters.AddWithValue("@messenger_id", messenger_id);
                thisCommand.Parameters.AddWithValue("@start_location", start_location);
                if (thisCommand.ExecuteNonQuery() > 0)
                {
                    thisConnection.Close();
                    return "true";
                }
                else
                {
                    thisConnection.Close();
                    return "false";
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                return e.StackTrace + " \n >>>>>>>>>>>>>>>>> \n" + e.Message;
            }
        }

        // DELETE api/location/5
        public void Delete(int id)
        {
        }
    }
}
